package com.xyq.friend.service.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xyq.common.core.constants.CacheConstants;
import com.xyq.common.core.constants.Constants;
import com.xyq.common.core.domain.LoginUser;
import com.xyq.common.core.domain.Result;
import com.xyq.common.core.domain.vo.LoginUserVO;
import com.xyq.common.core.enums.ResultCode;
import com.xyq.common.core.enums.UserIdentity;
import com.xyq.common.core.exception.ServiceException;
import com.xyq.common.core.utils.ThreadLocalUtil;
import com.xyq.common.sucurity.service.TokenService;
import com.xyq.friend.domain.user.User;
import com.xyq.friend.domain.user.dto.UserAddDTO;
import com.xyq.friend.domain.user.dto.UserLoginDTO;
import com.xyq.friend.domain.user.dto.UserUpdateDTO;
import com.xyq.friend.domain.user.vo.UserVO;
import com.xyq.friend.manager.UserCacheManager;
import com.xyq.friend.mapper.UserMapper;
import com.xyq.friend.utils.BCryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class UserServiceImpl implements UserService{
    @Value("${jwt.secret}")
    private String secret ;
    @Value("${file.oss.downloadImage}")
   private String downloadImage ;
    @Autowired
    private TokenService tokenService ;

    @Autowired
    private UserMapper userMapper ;

    @Autowired
    private UserCacheManager userCacheManager ;

    @Override
    public Result<String> register(UserAddDTO userAddDTO) {
        // 判断用户手机号是否存在
         if( userMapper.selectUserByPhone(userAddDTO.getPhone()) != null){
             throw new ServiceException(ResultCode.FAILED_USER_EXISTS);
         }
         if(!(userAddDTO.getPassword1().equals(userAddDTO.getPassword2()))){
             throw new ServiceException(ResultCode.FAILED_PASSWORD_DIFFERENT);
         }
         User user = new User() ;
         user.setPhone(userAddDTO.getPhone());
         user.setNickName(user.getPhone());
         // 注册默认给一个头像
        user.setHeadImage(CacheConstants.DEFAULT_HEAD_IMAGE);

         // 使用BCrypt 加密密码
       user.setPassword(BCryptUtils.encryptPassword(userAddDTO.getPassword1()));
         if( userMapper.insert(user) <= 0){
             return Result.fail();
         }
        return Result.success(
                tokenService.createToken(
                        user.getUserId(),secret , UserIdentity.ORDINARY.getValue(),user.getNickName() , user.getHeadImage()));
    }

    @Override
    public Result login(UserLoginDTO userLoginDTO) {
          User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                  .eq(User::getPhone,userLoginDTO.getPhone()));
         if(user == null ){
            return Result.fail(ResultCode.FAILED_USER_NOT_EXISTS) ;
        }else if(user.getStatus() == 0){
             throw new ServiceException(ResultCode.FAILED_USER_BANNED);
         }
         else if(BCryptUtils.matchesPassword(userLoginDTO.getPassword() , user.getPassword())){

            return Result.success(tokenService.createToken(
                    user.getUserId() , secret , UserIdentity.ORDINARY.getValue(),user.getNickName(), user.getHeadImage()));
        }
        // 身份验证失败

        return Result.fail(ResultCode.FAILED_LOGIN);
    }

    @Override
    public boolean logout(String token) {
        // 1.验证登录信息
        return tokenService.deleteLoginUser(token , secret);
    }

    // 获取当前用户信息
    @Override
    public Result info(String token) {
        // 获取当前用户对象
        LoginUser loginUser = tokenService.getLoginUser(token , secret) ;
        if(loginUser == null){
            return Result.fail();
        }
        LoginUserVO loginUserVO = new LoginUserVO() ;
        loginUserVO.setNickName(loginUser.getNickName());
        // 添加头像
        // 从 oss 获取 头像
     //  判断 用户头像是否为空
        if(StringUtils.hasLength(loginUser.getHeadImage())){
            loginUserVO.setHeadImage(downloadImage+loginUser.getHeadImage());
        }
        return Result.success(loginUserVO) ;
    }
   // 获取用户详细信息
    @Override
    public UserVO detail() {
         Long userId = ThreadLocalUtil.get(Constants.USER_ID , Long.class);
         // 如果没有用户id
         if(userId == null){
             throw new ServiceException(ResultCode.FAILED_USER_NOT_EXISTS);
         }
         // 查询缓存
         UserVO userVO = userCacheManager.getUserById(userId) ;
         if(userVO == null){
             throw new ServiceException(ResultCode.FAILED_USER_NOT_EXISTS);
         }
        // 添加头像
        // 从 oss 获取 头像
        //  判断 用户头像是否为空
        if(StringUtils.hasLength(userVO.getHeadImage())){
            userVO.setHeadImage(downloadImage+userVO.getHeadImage());
        }
        return userVO ;
    }

    @Override
    public int edit(UserUpdateDTO userUpdateDTO) {
          // 获取id
        Long userId = ThreadLocalUtil.get(Constants.USER_ID , Long.class);
        // 如果没有用户id
        if(userId == null){
            throw new ServiceException(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        // 查看数据库里的信息
        User user = userMapper.selectById(userId) ;
        if(user == null){
            throw new ServiceException(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        user.setNickName(userUpdateDTO.getNickName());
        user.setPhone(userUpdateDTO.getPhone());
        user.setEmail(userUpdateDTO.getEmail());
        user.setSex(userUpdateDTO.getSex());
        user.setIntroduce(userUpdateDTO.getIntroduce());
        user.setWechat(userUpdateDTO.getWechat());
        user.setSchoolName(userUpdateDTO.getSchoolName());
        user.setMajorName(userUpdateDTO.getMajorName());
        // 更新用户缓存
        userCacheManager.refreshUser(user);
        // 需要更新 用户的token 缓存
        tokenService.refreshLoginUser(user.getNickName() , user.getHeadImage()
               ,ThreadLocalUtil.get(Constants.USER_KEY , String.class)  );

        return userMapper.updateById(user);
    }

    @Override
    public int updateHeadImage(UserUpdateDTO userUpdateDTO) {
        // 获取id
        Long userId = ThreadLocalUtil.get(Constants.USER_ID , Long.class);
        // 如果没有用户id
        if(userId == null){
            throw new ServiceException(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        // 查看数据库里的信息
        User user = userMapper.selectById(userId) ;
        if(user == null){
            throw new ServiceException(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        // 更新头像信息
        user.setHeadImage(userUpdateDTO.getHeadImage());
        // 更新用户缓存 (用户详情缓存)
        userCacheManager.refreshUser(user);
        // 需要更新 用户的token 缓存
        tokenService.refreshLoginUser(user.getNickName() , user.getHeadImage()
                ,ThreadLocalUtil.get(Constants.USER_KEY , String.class)  );

        return userMapper.updateById(user);
    }

}
